package org.example

import kotlin.math.abs

fun isUniqueString(astr: String): Boolean {
    var temp = ""
    for (chat in astr.toCharArray()) {
        if (!temp.contains(chat)) {
            temp += chat
        }
    }
    return temp.length == astr.length
}

fun CheckPermutation(s1: String, s2: String): Boolean {
    if (s1.isEmpty() || s2.isEmpty() || s1.length != s2.length) {
        return false
    }
    return s1.toCharArray().sortedArray().contentEquals(s2.toCharArray().sortedArray())
}


fun replaceSpaces(S: String, length: Int): String {
    return S.substring(0, length).replace(" ", "%20");
}

fun canPermutePalindrome(s: String): Boolean {
    val charSet = HashSet<Char>()
    for (char in s.toCharArray()) {
        if (charSet.contains(char)) {
            charSet.remove(char)
        } else {
            charSet.add(char)
        }
    }
    return charSet.size <= 1
}

fun oneEditAway(first: String, second: String): Boolean {
    if (abs(first.length - second.length) > 1) {
        return false
    }

    if (first.contains(second) || second.contains(first)) {
        return true
    }

    if (first.length == second.length) {
        var wrongFlag = false
        for (i in first.indices) {
            if (first[i] != second[i]) {
                if (!wrongFlag) {
                    wrongFlag = true
                } else {
                    return false
                }
            }
        }
        return true
    } else {
        var skipFlag = false
        if (first.length < second.length) {
            for (index in first.indices) {
                val i = if (skipFlag) {
                    index - 1
                } else {
                    index
                }
                val j = index
                if (first[i] != second[j]) {
                    if (!skipFlag) {
                        skipFlag = true
                    } else {
                        return false
                    }
                }
            }
            return first.last() == second.last()
        } else {
            for (index in second.indices) {
                val i = if (skipFlag) {
                    index - 1
                } else {
                    index
                }
                val j = index
                if (second[i] != first[j]) {
                    if (!skipFlag) {
                        skipFlag = true
                    } else {
                        return false
                    }
                }
            }
            return first.last() == second.last()
        }
    }
}

fun compressString(S: String): String {
    val charMap = HashMap<Char, Int>()
    for (char in S.toCharArray()) {
        if (charMap.contains(char)) {
            val num = charMap[char]!!.plus(1)
            charMap[char] = num
        } else {
            charMap[char] = 1
        }
    }

    return S
}


fun main() {
    println(oneEditAway("teacher", "taches"))
}